package com.saltedfish.tool.handler;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Build;
import android.text.TextUtils;
import android.util.Log;

import androidx.core.app.NotificationCompat;

import com.saltedfish.tool.R;
import com.saltedfish.tool.model.SmallTable;
import com.saltedfish.tool.ui.MainActivity;
import com.saltedfish.tool.util.DateUtils;

import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import cn.droidlover.xdroidmvp.log.XLog;

public class NotificationUtil {

    private static final String TAG = "NotificationUtil";

    public static void  notificationByAlarm(Context context, SmallTable subFlagModel){
        int count = 1;
      //  SimpleDateFormat smf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
        Map<Integer,NotifyObject> notifyObjectMap = new HashMap<>();

        try {
          //  XLog.e("-111111----->>"+subFlagModel.toString());

            if(!TextUtils.isEmpty(subFlagModel.repeatDay)){
//                XLog.e("010101----->>"+subFlagModel.repeatDay);

                List<String> list = new ArrayList<>();
                String[] weeks = subFlagModel.repeatDay.split(" ");
                for (String week : weeks) {
//                    XLog.e("-11week----->>"+week);

                    list.addAll(DateUtils.getWeekly(subFlagModel.startTime,subFlagModel.endTime,week));
                }
                XLog.e("-2222----->>"+list.toString());

                String[] repeatTimes = subFlagModel.repeatTime.split("-");
//                if(list.size() !=0 && !TextUtils.isEmpty(subFlagModel.repeatTime)){
//                    for (String time:list) {
//                        NotifyObject objs = new NotifyObject();
//                        objs.type = subFlagModel.id;
//                        objs.title = subFlagModel.title;
//                        objs.subText = time +" 故事"+ repeatTimes[0];
//                        objs.content = time +" 结局"+ repeatTimes[0];
//                        objs.id = subFlagModel.id;
//                        objs.firstTime = time +" "+ repeatTimes[0] +":00";
//                        objs.activityClass = MainActivity.class;
//                        objs.icon = R.drawable.yd_bg;
//                        notifyObjectMap.put(objs.type,objs);
//                    }
//
//                    XLog.e("-333344---->>"+notifyObjectMap.toString());
//                    notifyByAlarm(context,notifyObjectMap,subFlagModel.id);
//
//                }

            }

        }catch (Exception e){

        }


    }

    /**
     * 通过定时闹钟发送通知
     * @param context
     * @param notifyObjectMap
     */
    public static void  notifyByAlarm(Context context, Map<Integer,NotifyObject> notifyObjectMap,int id){
        //将数据存储起来
        int count = 0;
       // NotificationManager manager = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);

        Set<Integer> keySet = notifyObjectMap.keySet();
        for (Integer key0: keySet) {
            if(!notifyObjectMap.containsKey(key0)){
                break;
            }

            NotifyObject obj = notifyObjectMap.get(key0);
            if(obj == null){
                break;
            }

            if(!TextUtils.isEmpty(obj.firstTime)){
                try {
                    Map<String, Serializable> map = new HashMap<>();
                    map.put("KEY_NOTIFY_ID",obj.id);
                    map.put("KEY_NOTIFY",NotifyObject.to(obj));
                    AlarmTimerUtil.setAlarmTimer(context,count++,obj.firstTime,"TIMER_ACTION",map);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

//            if(obj.times.size() <= 0){
//                if(!TextUtils.isEmpty(obj.firstTime)){
//                    try {
//                        Map<String, Serializable> map = new HashMap<>();
//                        map.put("KEY_NOTIFY_ID",obj.type);
//                        map.put("KEY_NOTIFY",NotifyObject.to(obj));
//                        AlarmTimerUtil.setAlarmTimer(context,++count,obj.firstTime,"TIMER_ACTION",map);
//                    } catch (IOException e) {
//                        e.printStackTrace();
//                    }
//                }
//            }else{
//                for (String time: obj.times) {
//                    if(!TextUtils.isEmpty(time)){
//                        try {
//                            Map<String,Serializable> map = new HashMap<>();
//                            map.put("KEY_NOTIFY_ID",obj.type);
//                            map.put("KEY_NOTIFY",NotifyObject.to(obj));
//                            AlarmTimerUtil.setAlarmTimer(context,++count,time,"TIMER_ACTION",map);
//                        } catch (IOException e) {
//                            e.printStackTrace();
//                        }
//                    }
//                }
//            }
        }

        SharedPreferences mPreferences = context.getSharedPreferences("SHARE_PREFERENCE_NOTIFICATION",Context.MODE_PRIVATE);
        SharedPreferences.Editor edit = mPreferences.edit();
        edit.putInt("KEY_MAX_ALARM_ID"+id,count);
        edit.commit();
    }

    public static void  notifyByAlarmByReceiver(Context context,NotifyObject obj){
        if(context == null || obj== null)return;
        NotificationManager manager = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
        notifyMsg(context,obj,obj.type,System.currentTimeMillis(),manager);
    }

    /**
     * 消息通知
     * @param context
     * @param obj
     */
    private static void notifyMsg(Context context,NotifyObject obj,int nid,long time,NotificationManager mNotifyMgr){
        if(context == null || obj == null)return;
        if(mNotifyMgr == null){
            mNotifyMgr =  (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
        }

        if(time <= 0)return;

        //准备intent

        Intent intent = new Intent(context,obj.activityClass);
        if(obj.param != null && obj.param.trim().length() > 0){
            intent.putExtra("param",obj.param);
        }

        //notification
        Notification notification = null;
        String contentText = obj.content;
        // 构建 PendingIntent
        PendingIntent pi = PendingIntent.getActivity(context, obj.id, intent, PendingIntent.FLAG_UPDATE_CURRENT);
        //版本兼容

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){//兼容Android8.0
            String id ="my_channel_01";
            int importance =NotificationManager.IMPORTANCE_LOW;
            CharSequence name = "notice";
            NotificationChannel mChannel =new NotificationChannel(id, name,importance);
            mChannel.enableLights(true);
            mChannel.setDescription("just show notice");
            mChannel.enableLights(true);
            mChannel.setLightColor(Color.GREEN);
            mChannel.enableVibration(true);
            mChannel.setVibrationPattern(new long[]{100,200,300,400,500,400,300,200,400});
            mNotifyMgr.createNotificationChannel(mChannel);

            Notification.Builder builder = new Notification.Builder(context,id);
            builder.setAutoCancel(true)
                    .setContentIntent(pi)
                    .setContentTitle(obj.title)
                    .setContentText(obj.content)
                    .setOngoing(false)
                    .setSmallIcon(obj.icon)
                    .setWhen(System.currentTimeMillis());
            if(obj.subText != null && obj.subText.trim().length() > 0){
                builder.setSubText(obj.subText);
            }
            notification =  builder.build();
        }else if (Build.VERSION.SDK_INT >= 23) {
            NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
            builder.setContentTitle(obj.title)
                    .setContentText(contentText)
                    .setSmallIcon(obj.icon)
                    .setContentIntent(pi)
                    .setAutoCancel(true)
                    .setOngoing(false)
                    .setWhen(System.currentTimeMillis());
            if(obj.subText != null && obj.subText.trim().length() > 0){
                builder.setSubText(obj.subText);
            }
            notification = builder.build();
        } else if ( Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN &&
                Build.VERSION.SDK_INT <= Build.VERSION_CODES.LOLLIPOP_MR1) {
            Notification.Builder builder = new Notification.Builder(context);
            builder.setAutoCancel(true)
                    .setContentIntent(pi)
                    .setContentTitle(obj.title)
                    .setContentText(obj.content)
                    .setOngoing(false)
                    .setSmallIcon(obj.icon)
                    .setWhen(System.currentTimeMillis());
            if(obj.subText != null && obj.subText.trim().length() > 0){
                builder.setSubText(obj.subText);
            }
            notification =  builder.build();
        }
        if(notification != null){
            mNotifyMgr.notify(obj.id+"",nid, notification);
        }
    }

    /**
     * 取消所有通知 同时取消定时闹钟
     * @param context
     */
    public static void clearAllNotifyMsg(Context context){
        try{

            NotificationManager mNotifyMgr =
                    (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
            mNotifyMgr.cancelAll();

            SharedPreferences mPreferences = context.getSharedPreferences("SHARE_PREFERENCE_NOTIFICATION",Context.MODE_PRIVATE);
            int max_id = mPreferences.getInt("KEY_MAX_ALARM_ID",0);
            for (int i = 1;i <= max_id;i++){
                AlarmTimerUtil.cancelAlarmTimer(context,"TIMER_ACTION",i);
            }
            //清除数据
            mPreferences.edit().remove("KEY_MAX_ALARM_ID").commit();

        }catch (Exception e){
            Log.e(TAG,"取消通知失败",e);
        }
    }


    /**
     * 取消所有通知 同时取消定时闹钟
     * @param context
     */
    public static void clearBySubIdNotifyMsg(Context context,int id){
        try{

            NotificationManager mNotifyMgr =
                    (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
//            mNotifyMgr.cancelAll();
            mNotifyMgr.cancel(id);
            SharedPreferences mPreferences = context.getSharedPreferences("SHARE_PREFERENCE_NOTIFICATION",Context.MODE_PRIVATE);
            int max_id = mPreferences.getInt("KEY_MAX_ALARM_ID"+id,0);
            for (int i = 1;i <= max_id;i++){
                AlarmTimerUtil.cancelAlarmTimer(context,"TIMER_ACTION",i);
            }
            //清除数据
            mPreferences.edit().remove("KEY_MAX_ALARM_ID"+id).commit();

        }catch (Exception e){
            Log.e(TAG,"取消通知失败",e);
        }
    }

}
